// stores/cart.js
import showPrompt from '@/utils/showPrompt'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  // 尝试从本地存储加载购物车数据
  const savedCart = localStorage.getItem('cart')
  const items = ref(savedCart ? JSON.parse(savedCart) : [])

  // 计算总价
  const totalPrice = computed(() => {
    const filterItems = items.value.filter(item => item.userId === userStore.userId)
    return filterItems
      .reduce((total, item) => {
        return total + item.price * item.quantity
      }, 0)
      .toFixed(2)
  })

  // 添加商品到购物车
  const addToCart = product => {
    const existingItem = items.value.find(item => item.id === product.id)

    if (existingItem) {
      existingItem.quantity++
    } else {
      items.value.push({
        ...product,
        quantity: 1,
        userId: userStore.userId
      })
      console.log(items.value)
    }
    saveCart()
  }

  // 增加商品数量
  const increaseQuantity = item => {
    item.quantity++
  }

  // 减少商品数量
  const decreaseQuantity = item => {
    if (item.quantity > 1) {
      item.quantity--
    }
  }

  // 删除商品
  const removeItem = id => {
    const index = items.value.findIndex(item => item.id === id)
    if (index !== -1) {
      items.value.splice(index, 1)
    }
    showPrompt('删除成功', 'success')
    localStorage.setItem('cart', JSON.stringify(items.value))
  }

  // 清空购物车
  const clearCart = () => {
    items.value = []
    localStorage.setItem('cart', JSON.stringify(items.value))
  }

  // 保存购物车到本地存储
  const saveCart = () => {
    localStorage.setItem('cart', JSON.stringify(items.value))
  }

  return {
    items,
    totalPrice,
    addToCart,
    increaseQuantity,
    decreaseQuantity,
    removeItem,
    clearCart
  }
})
